<!-- 登录注册窗口 -->

<script setup lang="ts">
import { useUserStore } from '@/stores/useUserStore';
import { useLoginStore } from '@/stores/useLoginStore';
import { ApiResponse, stringToApiResponse } from '@/types/apiResponse';
import service from '@/utils/axios';
import { ref, reactive, onMounted } from 'vue';
import { FormRules, FormInstance } from 'element-plus';

const userStore = useUserStore();
const loginStore = useLoginStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible'])

// 登录成功的提示
const loginSuccess = () => {
  ElMessage({
    message: '登录成功',
    type: 'success',
  })
}

// 登录失败的提示
const loginFailure = (failureMessage: string) => {
  ElMessage({
    message: failureMessage,
    type: 'warning',
  })
};

interface LoginForm {
  username: string;
  password: string;
}

onMounted(() => {
  userStore.loadUserInfo();
});

const loginForm = ref<LoginForm>({
  username: userStore.userInfo.username,
  password: '',
})

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  code: ''
})

const loginType = ref('account') // account | qrcode | phone
const isRegister = ref(false) // 是否显示注册页面
const loading = ref(false)

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  loginForm.value.password = '';
  registerForm.value = {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    code: ''
  }
  isRegister.value = false
}

// 登录接口
const login = async (username: string, password: string): Promise<ApiResponse<string>> => {
  const response = await service.post<string>('/user/login', {
    "username": username,
    "password": password
  });

  // 取service.post返回的数据的data字段将其转换为自定义响应类
  const apiResponse = stringToApiResponse(response.data);

  return apiResponse;
}

// 用户信息（此处衔接后端，因此数据结构与后端返回的形式一致）
interface BackUserInfo {
  id: number;
  nickname: string;
  profile: string;
  userType: number;
  token: string;
}

// 根据登录接口实现登录方法
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      console.log('submit!')
      loading.value = true
      try {
        const apiResponse = await login(loginForm.value.username, loginForm.value.password);
        if (apiResponse.code === 200) {
          await new Promise((resolve) => setTimeout(resolve, 200));
          // console.log('response：', apiResponse.data);

          // 将后端传来的数据进行序列化
          const backUserInfo: BackUserInfo = JSON.parse(JSON.stringify(apiResponse.data));

          userStore.setId(backUserInfo.id);
          userStore.setUsername(loginForm.value.username);
          userStore.setNickname(backUserInfo.nickname);
          userStore.setAvatar(backUserInfo.profile);
          userStore.setUserType(backUserInfo.userType);
          userStore.setToken(backUserInfo.token);
          userStore.setExpiration();
          userStore.isLogin = true;

          loginSuccess();
          await new Promise((resolve) => setTimeout(resolve, 500));
          window.location.reload();
          loginStore.closeLoginDialog();
        } else {
          loginForm.value.password = '';
          loginFailure(apiResponse.message);
          console.log('登录失败');
          
          await new Promise((resolve) => setTimeout(resolve, 500));
        };
      } catch (error) {
        console.error(error);

      } finally {
        loading.value = false
      }
    } else {
      console.log('error submit!')
      return
    }
  })


}

// 注册
const handleRegister = async () => {
  loading.value = true
  try {
    // TODO: 实现注册逻辑
    console.log('注册信息：', registerForm.value)
    await new Promise((resolve) => setTimeout(resolve, 500))
    handleClose()
  } finally {
    loading.value = false
  }
}

// 切换登录/注册
const toggleRegister = () => {
  isRegister.value = !isRegister.value
}

const ruleFormRef = ref<FormInstance>()

const infoRules = reactive<FormRules<LoginForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 20, message: '用户名不能超过20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { max: 20, message: '密码不能超过20个字符', trigger: 'blur' },
  ],
});

</script>

<template>
  <el-dialog :model-value="visible" @update:model-value="emit('update:visible', $event)"
    :title="isRegister ? '注册' : '登录'" width="400px" :close-on-click-modal="true" @close="handleClose">
    <div class="p-4">
      <!-- 登录页面 -->
      <template v-if="!isRegister">
        <!-- 登录方式切换 -->
        <div class="flex justify-center mb-8">
          <el-radio-group v-model="loginType">
            <el-radio-button value="account">账号密码</el-radio-button>
            <el-radio-button value="qrcode">扫码登录</el-radio-button>
            <el-radio-button value="phone">手机登录</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 账号密码登录 -->
        <template v-if="loginType === 'account'">
          <el-form ref="ruleFormRef" label-position="top" :rules="infoRules" :model="loginForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" prop="username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
                prop="password" show-password />
            </el-form-item>
            <el-form-item>
              <div class="flex items-center justify-between">
                <!-- <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox> -->
                <el-button link type="primary" class="forgot-password-button">忘记密码？</el-button>
              </div>
            </el-form-item>
          </el-form>
        </template>

        <!-- 扫码登录 -->
        <template v-else-if="loginType === 'qrcode'">
          <div class="text-center">
            <div class="inline-block p-4 bg-gray-50 rounded-lg mb-4">
              <el-image src="https://picsum.photos/200/200" class="w-[200px] h-[200px]" />
            </div>
            <p class="text-gray-500">请使用手机扫码登录</p>
          </div>
        </template>

        <!-- 手机登录 -->
        <template v-else>
          <el-form :model="loginForm" label-position="top">
            <el-form-item label="手机号">
              <el-input v-model="loginForm.username" placeholder="请输入手机号" prefix-icon="Iphone" />
            </el-form-item>
            <el-form-item label="验证码">
              <div class="flex gap-4">
                <el-input v-model="loginForm.password" placeholder="请输入验证码" prefix-icon="Message" />
                <el-button>获取验证码</el-button>
              </div>
            </el-form-item>
          </el-form>
        </template>

        <!-- 登录按钮 -->
        <el-button type="primary" class="w-full mt-4" :loading="loading" @click="handleLogin(ruleFormRef)">
          登录
        </el-button>

        <!-- 其他登录方式 -->
        <div class="mt-6">
          <div class="text-center text-gray-500 text-sm mb-4">其他登录方式</div>
          <div class="flex justify-center gap-8">
            <el-button circle class="!bg-blue-50 hover:!bg-blue-100">
              <el-icon color="#1677ff">
                <Position />
              </el-icon>
            </el-button>
            <el-button circle class="!bg-green-50 hover:!bg-green-100">
              <el-icon color="#07c160">
                <Promotion />
              </el-icon>
            </el-button>
            <el-button circle class="!bg-orange-50 hover:!bg-orange-100">
              <el-icon color="#ff6a00">
                <Orange />
              </el-icon>
            </el-button>
          </div>
        </div>

        <!-- 注册链接 -->
        <div class="text-center mt-6">
          <span class="text-gray-500">还没有账号？</span>
          <el-button link type="primary" @click="toggleRegister">立即注册</el-button>
        </div>
      </template>

      <!-- 注册页面 -->
      <template v-else>
        <el-form :model="registerForm" label-position="top">
          <el-form-item label="用户名">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
              show-password />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" prefix-icon="Lock"
              show-password />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" prefix-icon="Iphone" />
          </el-form-item>
          <el-form-item label="验证码">
            <div class="flex gap-4">
              <el-input v-model="registerForm.code" placeholder="请输入验证码" prefix-icon="Message" />
              <el-button>获取验证码</el-button>
            </div>
          </el-form-item>
        </el-form>

        <!-- 注册按钮 -->
        <el-button type="primary" class="w-full mt-4" :loading="loading" @click="handleRegister">
          注册
        </el-button>

        <!-- 返回登录 -->
        <div class="text-center mt-6">
          <span class="text-gray-500">已有账号？</span>
          <el-button link type="primary" @click="toggleRegister">返回登录</el-button>
        </div>
      </template>
    </div>
  </el-dialog>
</template>

<style lang="less" scoped>
:deep(.el-dialog__body) {
  padding: 0;
}

.forgot-password-button {
  margin-left: 20px;
}
</style>
